package com.lge.clock.worldclock;
import java.util.*;
import java.io.IOException;
import java.util.ArrayList;

import javax.microedition.khronos.opengles.GL;

import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Color;
import android.opengl.GLSurfaceView;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.util.DisplayMetrics;
import android.view.ContextThemeWrapper;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.*;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lge.clock.R;
import com.lge.clock.WorldClockFragment;
import com.lge.clock.util.CommonUtil;
import com.lge.clock.util.EmGubunMedit;
import com.lge.clock.util.ThMeditate;
import com.lge.clock.util.CommonUtil.OPERATOR;
import com.lge.clock.worldclock.cities.CityDBManager;
import com.lge.clock.worldclock.cities.CityInfoDisplay;
import com.lge.clock.worldclock.cities.CityInformation;
import com.lge.clock.worldclock.map.EarthRenderer;
import com.lge.clock.worldclock.map.EarthView;
import com.lge.clock.worldclock.map.MatrixTrackingGL;
import com.lge.clock.worldclock.util.DataManager;
import com.lge.clock.worldclock.util.Log;
import com.lge.clock.worldclock.util.WCPreferences;

/**
 * @author lge.com
 */
public class MapSearchActivity extends Activity implements OnClickListener, OnTouchListener {
	private static final String PREFIX = "Earth3D";
    
	private EarthView mEarthView;
	private LinearLayout mEarthLayout;
	
	private ImageButton mZoomInButton;
	private ImageButton mZoomOutButton;

	private ActionBar actionBar;
	private long mBeforClickedTime = 0;
	private long mAfterClickedTime = 0;
	/**
	 * Field mIsLoadCompleteShapeData.
	 */
	public static boolean mIsLoadCompleteShapeData = false;
    private GestureDetector mGestureDetector;
    
    //[suhaeng.lee][6399] 2012.04.16 START
    public static boolean bXhdpi = false;
	public static boolean bHdpi = false;
	public static boolean bMdpi = false;
	public static boolean bLdpi = false;
	//[suhaeng.lee][6399] 2012.04.16 END
    
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
        	if(mEarthView != null) {
        		mEarthView.requestLayout();
        	}
        }
    };
    
	/**
	 * Method onCreate.
	 */
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.message(PREFIX, "onCreate() - S");
        
        //[suhaeng.lee][6399] 2012.04.16
        getDisplayMetrics();
        
        actionBar = getActionBar();
	    actionBar.setTitle(R.string.sp_NEWCITY_NORMAL);
	    actionBar.setIcon(R.drawable.world_clock);
	    actionBar.setDisplayShowHomeEnabled(true);
        WCPreferences wcPref = new WCPreferences(this);
        wcPref.setSearchType(false);
        try {
        	if (!mIsLoadCompleteShapeData) {
        		DataManager.loadLCDSize(this);
        		DataManager.loadAssetsBinaryFile(this);
            	mIsLoadCompleteShapeData = true;
        	}
        } catch (Exception e) {
        	e.printStackTrace();
        }
        
        if (mIsLoadCompleteShapeData) {
            setContentView(R.layout.worldclock_map_search);
            
            mEarthLayout = (LinearLayout)findViewById(R.id.earthview);
            mEarthView = new EarthView(this.getApplicationContext());

            mEarthView.setGLWrapper(new GLSurfaceView.GLWrapper() {
                public GL wrap(GL gl) {
                    return new MatrixTrackingGL(gl);
                }});

            mEarthLayout.addView(mEarthView);
            mEarthView.setOnTouchListener(this);
            mEarthView.setFocusable(true);
            gestureDetector();
            mZoomInButton = (ImageButton)findViewById(R.id.zoom_plus_btn);
            mZoomOutButton = (ImageButton)findViewById(R.id.zoom_minus_btn);
            mZoomInButton.setOnClickListener(this);
            mZoomOutButton.setOnClickListener(this);
        }
        
        buttonEnableSetting();
        Log.message(PREFIX, "onCreate() - E");
    }
	
	
	/**
	 * Method onConfigurationChanged.
	 * @see android.content.ComponentCallbacks#onConfigurationChanged(Configuration) */
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		mHandler.sendEmptyMessageDelayed(0, 100);
	}
	
	/**
	 * Method onResume.
	 */
	@Override
	protected void onResume() {
	    Log.message(PREFIX, "onResume() - S");
		super.onResume();
		if (mEarthView != null) {
		    mEarthView.onResume();
		    mHandler.sendEmptyMessageDelayed(0, 100);
		}
		Log.message(PREFIX, "onResume() - E");
	}

	/**
	 * Method onPause.
	 */
	@Override
	protected void onPause() {
		super.onPause();
		
		if (mEarthView != null) {
		    mEarthView.onPause();
		}
	}
	MenuItem mPlusMenu;
	MenuItem mMinusMenu;
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.clear();
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.worldclock_map_menu,menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch(item.getItemId()){
		case R.id.list_search_btn:
			
			item.setEnabled(false);
			
			if(!CommonUtil.MAP_LEAVE_FLAG){
				break;
			}
			
//			long mTimeGap = 0;
//			
//			mAfterClickedTime = SystemClock.elapsedRealtime();
//			mTimeGap = mAfterClickedTime - mBeforClickedTime;
//			if (mTimeGap < ViewConfiguration.getDoubleTapTimeout() * 3) {
//				break;
//			} else {
//				mBeforClickedTime = SystemClock.elapsedRealtime();
//			}
			
    		CommonUtil.ENTER_EXECUTOR.execute(new ThMeditate(CommonUtil.MAP_DELAY_ENTER_TIME, EmGubunMedit.MAP_ENTER));
	        finish();
			Intent list_intent = new Intent(this, ListSearchActivity.class);
			list_intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(list_intent);
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		super.onPrepareOptionsMenu(menu);
		return true;
	}
	
	/**
	 * Method onWindowFocusChanged.
	 * @see android.view.Window$Callback#onWindowFocusChanged(boolean) 
	 * */
	@Override
	public void onWindowFocusChanged(boolean hasFocus) {
		super.onWindowFocusChanged(hasFocus);
    	if (mIsLoadCompleteShapeData) {
    		DataManager.loadLCDSize(this);
    		DataManager.loadDisplayFrameInfo(getWindow());
    	}
	}
	
	/**
	 * Method onClick.
	 * @see android.view.View$OnClickListener#onClick(View) 
	 * */
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.zoom_plus_btn:
		    mEarthView.zoomInEarth();
		    buttonEnableSetting();
		    break;
		case R.id.zoom_minus_btn:
		    mEarthView.zoomOutEarth();
		    buttonEnableSetting();
		    break;
		default :
		}
	}

	private void buttonEnableSetting()
	{
		float status = mEarthView.getcurrentzoomStatus();
		float minSize = EarthRenderer.SHAPE_SCALE_MINIMUM_SIZE;
		float maxSize = EarthRenderer.SHAPE_SCALE_MAXIMUM_SIZE;
		
		int result1 = Float.compare(status, minSize);
		int result2 = Float.compare(status, maxSize);
		if(result1 == 0) {
			mZoomOutButton.setEnabled(false);
	    	mZoomInButton.setEnabled(true);
		} else if(result2 == 0) {
			mZoomOutButton.setEnabled(true);
	    	mZoomInButton.setEnabled(false);
		} else {
	    	mZoomOutButton.setEnabled(true);
	    	mZoomInButton.setEnabled(true);
	    }
	}
	
	/**
	 * Method onTouch.
	 * @see android.view.View$OnTouchListener#onTouch(View, MotionEvent) */
	public boolean onTouch(View view, MotionEvent event) {
		if(mEarthView.equals(view)) {
	        if (mGestureDetector != null) {
	            if (mGestureDetector.onTouchEvent(event)) {
	                return true;
	            }
	        }
	        buttonEnableSetting();
			return mEarthView.onTouchEvent(event);
		}
		return false;
	}
	
	private void gestureDetector() {
        mGestureDetector = new GestureDetector(getApplicationContext(), new GestureDetector.SimpleOnGestureListener() {

            public boolean onSingleTapUp(MotionEvent e) {
				if(EarthRenderer.getCurrentScale() < EarthRenderer.DISPLAY_SHAPE_SCALE_LEVEL_1) return false;
                
				CityInfoDisplay displayCityInfo = mEarthView.getDisplayCityInfo();
				
                if (displayCityInfo.isSelectedCity(e)) {
                    ArrayList<CityInformation> selectCityInfoList = displayCityInfo.getSelectedCityInfoList();
                    if (selectCityInfoList != null && selectCityInfoList.size() > 0) {
                    	mEarthView.setEnabled(false);
                        showSelectCityDialog(selectCityInfoList);
                        return true;
                    } else {
                        return false;
                    }
                }
                return false;
            }
        });
    }
	
	private void showSelectCityDialog(final ArrayList<CityInformation> cityInfoList) {        
		final Context dialogContext = new ContextThemeWrapper(this, android.R.style.Theme_Light);
		final LayoutInflater dialogInflater = 
				(LayoutInflater)dialogContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		
		final ArrayAdapter<CityInformation> cityAdapter = new ArrayAdapter<CityInformation>(this,
				android.R.layout.simple_list_item_1, cityInfoList) {
			
			@Override
			public View getView(int position, View convertView, ViewGroup parent) {
				if (convertView == null) {
					convertView = dialogInflater.inflate(
							android.R.layout.simple_list_item_1, parent, false);
				}
				
				final TextView textView = (TextView) convertView.findViewById(android.R.id.text1);
				
				final CityInformation item = this.getItem(position);
				textView.setText(item.getCityName() + ", " + item.getCountryName());
				textView.setTextColor(Color.parseColor(getResources().getString(R.color.list_PrimaryFontColor)));
				return convertView;
			}
		};
		
		final DialogInterface.OnClickListener clickListener = new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				final CityInformation selectedItem = cityInfoList.get(which);
				int id = selectedItem.getID();
				
				try {
					CityDBManager dbManager = CityDBManager.getInstance(getBaseContext());
					
					if(!isVerifyCheck(id, dbManager)) {
						
						if(CommonUtil.isSprintOperator()){
							Toast.makeText(getApplicationContext(), getString(R.string.sp_msg_dup_city_list_NORMAL, selectedItem.getCityName()), Toast.LENGTH_SHORT).show();
						}else{
							Toast.makeText(getBaseContext(), R.string.msg_dup_city_list, Toast.LENGTH_SHORT).show();
						}

					}
					else {
						Intent intent = new Intent(getBaseContext(), WorldClockFragment.class);
						dbManager.addCityInfo(id);
						intent.putExtra("_id", id);
						setResult(RESULT_OK, intent);
						finish();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
				
				dialog.dismiss();
			}
		};
		
		/*[START] 2011.12.15 suein1209.kim INTERNAL_TEST.SDQ_11 - Defect #106759 : Change the string*/
		AlertDialog dialog = new AlertDialog.Builder(this).setTitle(R.string.sp_select_city_NORMAL)
		/*[END] 2011.12.15 suein1209.kim INTERNAL_TEST.SDQ_11 - Defect #106759 : Change the string*/
		.setSingleChoiceItems(cityAdapter, -1, clickListener).show();
		
		final DialogInterface.OnDismissListener dismissListener = new DialogInterface.OnDismissListener() {
			@Override
			public void onDismiss(DialogInterface dialog) {
				// TODO Auto-generated method stub
				mEarthView.setEnabled(true);
			}
		};
		dialog.setOnDismissListener(dismissListener);
	}
	
	private boolean isVerifyCheck(int id, CityDBManager dbManager) {
		ArrayList<CityInformation> tempCityArray;
		tempCityArray = dbManager.getWorldClockList(this);

		for(CityInformation item : tempCityArray) {
			if(item.getID() == id) return false;
		}
		
		return true;
	}

	//[suhaeng.lee][5828] 2012.04.11 for no effect on menu_key START
	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		
		switch (keyCode) { 		
		case KeyEvent.KEYCODE_MENU :

			return true;
		
		default :
			break;
		} 
		
		return super.onKeyUp(keyCode, event);
	}
	//[suhaeng.lee][5828] 2012.04.11 for no effect on menu_key END
	
	
	//[suhaeng.lee][6399] 2012.04.16 START
	public void getDisplayMetrics(){
	    DisplayMetrics displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        
        
        int deviceWidth = displayMetrics.widthPixels;
        int deviceHeight = displayMetrics.heightPixels;
        int deviceDpi = displayMetrics.densityDpi;
        
        Log.message(PREFIX, "deviceWidth = " + deviceWidth + "px");
        Log.message(PREFIX, "deviceHeight = " + deviceHeight + "px");
        Log.message(PREFIX, "deviceDpi = " + deviceDpi + "px");
        
        if(deviceDpi > 270){
            bXhdpi = true;
            bHdpi = false;
            bMdpi = false;
            bLdpi = false;
        } else if(deviceDpi > 160 && deviceDpi <= 270){
            bXhdpi = false;
            bHdpi = true;
            bMdpi = false;
            bLdpi = false;
        } else if(deviceDpi > 120 && deviceDpi <= 160){
            bXhdpi = false;
            bHdpi = false;
            bMdpi = true;
            bLdpi = false;
        } else {
            bXhdpi = false;
            bHdpi = false;
            bMdpi = false;
            bLdpi = true;
        }
	}
	//[suhaeng.lee][6399] 2012.04.16 END
	
}